package com.fagp.mew.cms.controller.permission;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fagp.mew.cms.messages.PageRequest;
import com.fagp.mew.cms.messages.PageResponse;
import com.mew.common.dc.mapper.PermissionMapper;
import com.mew.common.dc.mapper.RoleMapper;
import com.mew.common.entity.back.Role;
import com.mew.common.util.StringUtils;
import com.mew.common.vo.web.RolePermVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.security.RolesAllowed;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RolesAllowed({"ADMIN"})
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @ResponseBody
    @RequestMapping("/all")
    public PageResponse all(PageRequest p){
        List<Role> roles = roleMapper.selectList(new QueryWrapper<>());
        return new PageResponse(roles);
    }


    @ResponseBody
    @RequestMapping("/perm")
    public PageResponse perm(PageRequest p){

        ArrayList<RolePermVo> rolePerms = permissionMapper.findRolePerms();
        List<RolePermVo> vos = rolePerms.stream().collect(Collectors.toMap(RolePermVo::getId, r -> r, (r1, r2) -> {
            r1.setPid(r1.getPid() + "," + r2.getPid());
            r1.setPname(r1.getPname() + " " + r2.getPname());
            return r1;
        })).values().stream().collect(Collectors.toList());
        return new PageResponse(vos);
    }

    @ResponseBody
    @RequestMapping("/upperm")
    public PageResponse upperm(Integer roleId,Integer[] permIds){
        roleMapper.delPerm(roleId);
        if (null!=permIds){
            for (Integer permId : permIds) {
                roleMapper.addPerm(roleId,permId);
            }
        }
        return new PageResponse();
    }

    @ResponseBody
    @RequestMapping("/add")
    public PageResponse add(Role role){
        //更新
        if (null!=role.getId()){
            roleMapper.updateById(role);
        }else {
            if (StringUtils.isNotEmpty(role.getName())){
                roleMapper.insert(role);
            }
        }
        return new PageResponse();
    }

}
